import React, {
	Component
} from "react";
import {
	View,
	Text,
	TextInput,
	TouchableOpacity,
	Alert,
	Image,
	Keyboard,
} from "react-native";
import Button from "apsl-react-native-button";
import {
	observer
} from "mobx-react";
import SearchData from "../models/SearchData";
import {
	StackNavigator
} from "react-navigation";
//引入loading加载图标；
import Loading from "../components/Loading";
import styles from "./style";

@observer
class SearchPage extends Component {
	constructor(props) {
		super(props);
		this.handleSearch = this.handleSearch.bind(this);
		this.handleChange = this.handleChange.bind(this);
	}
	onLocationPressed() {
			SearchData.searchString.isLoading = true;
			navigator.geolocation.getCurrentPosition(
				location => {
					var search = location.coords.latitude + ',' + location.coords.longitude;
					SearchData.searchString.houseAddress = search;
					var query = SearchData.urlForQueryAndPage('centre_point', search, 1);
					SearchData.getLocationFetch(query).then(() => {
						SearchData.searchString.isLoading = false;
						this.props.store();
					});
				},
				error => {
					this.setState({
						message: 'There was a problem with obtaining your location: ' + error
					});
				});
		}
		//获取搜索框中的内容；
	handleChange(event) {
			if (event.nativeEvent.text == "") {
				SearchData.searchString.isLoading = false;
				SearchData.searchString.houseAddress = "";
			} else {
				SearchData.searchString.houseAddress = event.nativeEvent.text;
			}
		}
		//搜索触发事件；
	handleSearch() {
		SearchData.searchString.isLoading = true;
		Keyboard.dismiss();
		//请求数据；
		SearchData.getFetch().then(() => {
			if (!SearchData.searchString.message) {
				this.props.store();
			}
		});
	}
	render() {
		const {
			isLoading,
			houseAddress,
			message,
		} = SearchData.searchString;
		return (
			<View style={styles.container}>
				<Text style={[styles.fontSize16, styles.description]}>
					Search for houses to buy!
				</Text>
				<Text style={[styles.fontSize16, styles.description]}>
					 Search by place-name, postcode or search near your location.
				</Text>
				<View style={styles.row}>
					<TextInput
					style={styles.textInput}
					placeholder="Search via name or postcode"
					onChange={this.handleChange}
					underlineColorAndroid="transparent"
					/>
					<TouchableOpacity style={styles.button1} onPress={this.handleSearch}>
						<Text style={styles.goButton}>
							GO
						</Text>
					</TouchableOpacity >
				</View>
				<Button 
					style={styles.button2} 
					textStyle={{fontSize: 16, color: "#fff"}}
					onPress={this.onLocationPressed.bind(this)}
				>
					Location
				</Button>
				<Image source={require('../images/house.png')} />
				{ isLoading ? (<Loading />) : (<View />) }
				<Text style={styles.warnText}>{message}</Text>
			</View>
		);
	}
}
export default SearchPage;